package com.tastespot.utils.lock.impl;


import cn.hutool.core.lang.UUID;
import com.tastespot.utils.lock.Lock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;


/**
 * @Author: 369pro
 * @CreateTime: 2025-05-22
 * @Version: 1.0
 */
public class SimpleRedisLock implements Lock {
    private static final String KEY_PREFIX="lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    private StringRedisTemplate stringRedisTemplate;
    // 用的时候为userId, 一个用户只能下一单
    private String name;

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String name){
        this.stringRedisTemplate = redisTemplate;
        this.name = name;
    }

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    /**
     * 【防止锁误删问题】：获取锁时存入线程标识
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // SET lock:name threadId EX timeoutSec NX
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    /**
     * 释放锁的时候判断锁是不是自己的
     */
    @Override
    public void unlock() {
//        String threadId = ID_PREFIX + Thread.currentThread().getId();
//        String curId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        if(threadId.equals(curId)){
//            // note 8. 判断与删除并非原子操作，仍然存在误删问题
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }
}
